#include "api/stdafx.hpp"
#include "api/grc_geometryengine.hpp"
#include "game_controller/ih/game_controller_iscene.hpp"
#include "game_model/headers/game_model_distance_unit.hpp"

namespace GraphicConnector {

GeometryEngine::GeometryEngine( QWidget *parent )
	:	m_graphicScene( parent )
{
}

GeometryEngine::~GeometryEngine()
{
}

void
GeometryEngine::paintGL()
{
	setViewport( parentWidget() );
}


void
GeometryEngine::initTexture( GameModel::IObject::Ptr _object )
{
	QGraphicsPixmapItem* item = m_graphicScene.addPixmap( QPixmap::fromImage( *_object->getImage() ) );
	item->setX( _object->getCurrentLocation().getHorizontalLocation().getPlainData()*10 );
	item->setY( _object->getCurrentLocation().getVerticalLocation().getPlainData()*10 );
}

void
GeometryEngine::resizeGL(int w, int h)
{
	/*// Set OpenGL viewport to cover whole widget
	glViewport(0, 0, w, h);
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();

	// Calculate aspect ratio
	qreal aspect = qreal(w) / qreal(h ? h : 1);

	// Set near plane to 3.0, far plane to 7.0, field of view 45 degrees
	const qreal zNear = 3.0, zFar = 7.0, fov = 45.0;

	// Reset projection
	projection.setToIdentity();

	projection.lookAt(
			QVector3D( 0.0, 0.0, -8.0 )
		,	QVector3D( 0.0, 0.0, 0.0 )
		,	QVector3D( 0.0, 1.0, 0.0 )
		);*/
}

void
GeometryEngine::setScene( GameController::IScene::Ptr _scene )
{
	m_scene.reset();
	// Clear color and depth buffer
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	auto it = _scene->getObjects().begin();
	for( ; it != _scene->getObjects().end(); ++it )
		initTexture( *it );

	m_graphicScene.setBackgroundBrush( *_scene->getBackground() );

	m_scene = _scene;
	QGraphicsView::setScene( &m_graphicScene );
}

} // namespace GraphicConnector